<template>
  <vxe-modal
v-model="insideShow" 
  ref="xModal"
  destroy-on-close 
  resize show-zoom esc-closable showFooter
  width="clamp(400px, 100%, 1200px)"
  size="medium"
  height="78%"
  :lock-scroll="false"
  @show="onShow"
  @hide="onClose"
  @close="onClose">
    <template #title>
      <span>选择商品</span>
      <span style="padding-left: 36px;font-size: .3rem;font-weight: normal;">
        当前已选择 <span style="color:red;font-weight: bold;">{{checkedList.length}}</span> 个商品
      </span>
    </template>
    <template #default>
      <splitpanes class="default-theme" id="splitpanes">
        <pane min-size="24" max-size="30" size="24">
          <CateSide @select-change="handleSelectChange" />
        </pane>
        <pane>
          <vxe-grid 
          ref="xGrid" v-bind="gridOptions" class="myGrid-style"
            @keydown="onKeydownOfXGrid"
            @checkbox-change="checkboxChange"
            @checkbox-all="checkboxAll"
            @checkbox-range-change="checkboxRangeChange"
            @cell-dblclick="dblclick">
              <template #form>
                <slot name="form"></slot>
              </template>

              <template #toolbar_buttons>
                <vxe-form 
                :data="insideQueryParams" @reset=""
                :style="{width: 'clamp(250px,100%,330px)'}">
                  <vxe-form-item span="24">
                    <template #default>
                      <vxe-input
                      v-model="insideQueryParams.word" type="text" clearable
                      suffix-icon="vxe-icon-search"
                      placeholder="编号、条形码、名称、规格"
                      @keydown="onKeydown"
                      @clear="onClear"/>
                    </template>
                  </vxe-form-item>
                </vxe-form>
              </template>

              <!-- <template #qty_edit="{ row }">
                <vxe-input v-model="row.qty" type="float" min="0" digits="0" step="1" 
                :controls="true"
                :disabled="!row.enable"
                @dblclick.native="handleQtyDbClick"
                @click="handleQtyClick"
                @prev-number="handleQtyClick"
                @next-number="handleQtyClick"
                @suffix-click="handleQtyClick" />
              </template> -->
          </vxe-grid>
        </pane>
      </splitpanes>
    </template>
    
    <template #footer>
      <vxe-button content="取消" @click="onCloseOfSelected(false)" />
      <vxe-button status="primary" content="确定" @click="onCloseOfSelected(true)" />
    </template>
  </vxe-modal>
</template>
<script lang="ts" name="GoodsModal" setup>
import __ from 'lodash-es';
import { Pane, Splitpanes } from 'splitpanes';
import { reactive, ref, toRaw, watch } from 'vue';
import { VxeGridPropTypes, VxeGridProps } from 'vxe-table';
import CateSide from './CateSide.vue';
import { columns, pagerConfig } from './data';
import { getTableData } from '/@/api/wms/goods';

const props = defineProps({
  show: Boolean,
  queryParams: {type: Object, default: {}},
  queryApi: Function,
})

const insideQueryParams = reactive({
  word: '',
  cateId: 0,
});

const reload = () => {
  loadingRef.value = true
  let {pager} = xGrid.value.getProxyInfo()
  let query = Object.assign({}, toRaw(insideQueryParams), pager)
  getTableData(query).then((dd:any) => {
    xGrid.value.loadData(dd?.result)
    pager.total = dd?.page?.total
  }).finally(() => {
    loadingRef.value = false
    xGrid.value.focus()
  })
}

const xModal = ref()
const xGrid = ref()
const loadingRef = ref(false)
const gridOptions = reactive<VxeGridProps>({
  loading: loadingRef.value,
  border: true,
  resizable: true,
  showHeaderOverflow: true,
  showOverflow: false,
  highlightHoverRow: true,
  keepSource: true,
  id: 'xGrid_modalOfGoods',
  stripe: true,
  // height: window.innerHeight - 180,
  height: '120%',
  size: 'medium',
  rowId: 'id',
  rowClassName: ({ row, }) => {
    if (row.enable !== 1) {
      return 'row-enable'
    }
    return null
  },
  columns: columns as VxeGridPropTypes.Columns,
  columnConfig: {
    useKey: true,
    isCurrent: true,
    isHover: true,
  },
  rowConfig: {
    useKey: true,
    isCurrent: true,
    isHover: false,
    keyField: 'ID',
  },
  keyboardConfig: {isArrow: true, isEnter: true,},
  customConfig: {
    storage: true,
  },
  tooltipConfig: {
  },
  sortConfig: {
    trigger: 'cell',
    remote: false
  },
  filterConfig: {
    remote: false
  },
  pagerConfig: pagerConfig,
  toolbarConfig: {
    // refresh: {query: reload,},
    zoom: false,
    custom: true,
    slots: {
      buttons: 'toolbar_buttons',
    },
  },
  checkboxConfig: {
    reserve: true,
    highlight: true,
    range: true,
    trigger: 'row',
    checkStrictly: false,
    checkMethod: ({row}) => {
      return row.enable === 1
    },
  },
  proxyConfig: {
    autoLoad: true,
    ajax: {
      query({ page, sort, sorts, filters, form }) {
        if (props.queryApi) {
          let params = Object.assign({}, toRaw(props.queryParams), insideQueryParams, page)
          return props.queryApi(params)
        }
        // return getTableData(query);
      },
    }
  },
});

const onKeydownOfXGrid = ({ $event }) => {
  if ($event.keyCode === 13) {
    let row = xGrid.value.getCurrentRecord()
    if (row && row.enable !== 0) {
      let checked = xGrid.value.isCheckedByCheckboxRow(row)
      if (!checked) {
        checkedList.value.push(row)
      } else {
        __.remove(checkedList.value, function(e:any) {
          return e.ID === row.ID;
        });
      }
      xGrid.value.setCheckboxRow(row, !checked)
    }
  }
}

const checkedList = ref<any>([])

const checkboxChange = ({ checked, row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, $event }) => {
  if (!checked) {
    __.remove(checkedList.value, function(e:any) {
      return e.ID === row.ID;
    });
  } else {
    checkedList.value.push(row)
  }
}
const checkboxAll = ({ checked, $event }) => {
  if (!checked) {
    checkedList.value.length = 0
    checkedList.value.push(...xGrid.value.getCheckboxReserveRecords(true))
  } else {
    let list = xGrid.value.getCheckboxRecords(true)
    list.forEach(e => {
      if (!checkedList.value.some(cl => cl.ID === e.ID)) {
        checkedList.value.push(e)
      }
    })
  }
}
const checkboxRangeChange = ({}) => {
  let list1 = xGrid.value.getCheckboxRecords(true)
  let list2 = xGrid.value.getCheckboxReserveRecords(true)
  checkedList.value.length = 0
  checkedList.value.push(...list1)
  checkedList.value.push(...list2)
}

const dblclick = ({ row, }) => {
  if (row.enable === 1) {
    xModal.value.close().finally(() => emits('on-close-of-selected', [toRaw(row)]))
  }
}

const emits = defineEmits(['on-close', 'on-close-of-selected',]);

const handleSelectChange = (list:any) => {
  insideQueryParams.cateId = (list.length > 0) ? list[0] : 0
  reload()
}

const insideShow = ref(false)
watch(()=>props.show, (v1, _) => {
  insideShow.value = v1
}, {immediate: true})
const modalHeight = ref(600)
const onShow = ({}) => {
  xGrid.value.focus()
  modalHeight.value = window.innerHeight - 100
}
const onClose = ({}) => {
  insideQueryParams.word = ''
  insideQueryParams.cateId = 0
  checkedList.value = []
  xGrid.value?.clearCheckboxRow()
  xGrid.value?.clearCheckboxReserve()
  emits('on-close')
}

const onCloseOfSelected = (selected:Boolean) => {
  emits('on-close-of-selected', selected ? toRaw(checkedList.value) : [])
  xModal.value.close()
}

const onKeydown = ({ $event }) => {
  if ($event.keyCode === 13) {
    $event.stopPropagation() // 必须阻止冒泡,不然会同时触发xgrid的keydown
    reload()
  }
}

const handleQtyClick = ({ value, $event }) => {
  $event.stopPropagation()
}

const handleQtyDbClick = ($event) => {
  $event.stopPropagation()
}

const onClear = ({}) => {
  reload()
}
</script>

<style scoped>
:deep().myGrid-style .vxe-body--row.row-enable {
  opacity: .51;
}
</style>
